<script setup>
import api from './api.js'
import deviceApi from '@/api/device.js'

const { proxy } = getCurrentInstance();

const openFlag = ref(false);
const rfidList = ref([]);

let socket = null;

function createWebsocket() {
  socket = deviceApi.createWebsocket('rfid', (data)=> {
    const list = rfidList.value;
    if (list.indexOf(data) === -1) {
      list.push(data);
    }
  });
}

function closeWebsocket() {
  if (socket) {
    socket.close();
  }

}

function startInventory() {
  api.inventory().then(response => {
    proxy.$modal.msgSuccess("开始盘点");
  })
}

function stopInventory() {
  api.stopInventory().then(response => {
    proxy.$modal.msgSuccess("停止盘点");
  })
}

function open(id) {
  // 创建WebSocket监听RFID的读取
  openFlag.value = true;
  rfidList.value = [];
  createWebsocket();
  // 发送盘点请求
  startInventory();
}

function close() {
  openFlag.value = false;
}

function onClose() {
  stopInventory();
  closeWebsocket();
}

// 外部使用的属性或方法
defineExpose({
  open
})
</script>

<template>

  <div>
    <el-dialog width="500" height="500" title="RFID盘点" v-model="openFlag" align-center top="50" @close="onClose">
      <div>
        <el-button type="primary" @click="startInventory">盘点</el-button>
        <el-button type="primary" @click="stopInventory">停止盘点</el-button>
      </div>
      <div style="height: 300px">
        <ul>
          <li v-for="rfid in rfidList">{{rfid}}</li>
        </ul>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-row type="flex" justify="end">
          <el-button @click="close">关闭</el-button>
        </el-row>

      </div>
    </el-dialog>
  </div>


</template>

<style scoped lang="scss">

</style>